import Vue from 'vue';
import Router from 'vue-router';
import auth from '@/utils/auth';
import TheLayout from '@/components/layout';
import Root from '@/views/root';
import ViewUI from 'view-design';
import consts from '@/utils/consts';
import store from '@/store';

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: '/',
      component: Root,
      children: [
        {
          path: '/',
          component: TheLayout,
          children: [
            require('./routes/home').default,
            require('./routes/index-manage').default,
            require('./routes/user-manage').default,
            require('./routes/admin').default,
            require('./routes/book-manage').default,
            require('./routes/price-manage').default,
            require('./routes/friend-help').default,
            require('./routes/comment-manage').default,
            require('./routes/notice-manage').default,
            require('./routes/setting-manage').default,
          ],
          meta: {
            requiresAuth: true
          }
        },
        {
          path: '/',
          component: TheLayout,
          children: [
            require('./routes/error-page').default
          ]
        },
        require('./routes/login').default,
        require('./routes/logout').default
      ]
    },
    {
      path: '*',
      redirect: '/error-page/404'
    }
  ]
});

const findRouteTitle = (datas, matched) => {
  let result = '';
  for (let i = 0; i < datas.length; i++) {
    if (matched.some(item => item.path === datas[i].route)) {
      result = datas[i].title;
    }
    if (datas[i].children && datas[i].children.length > 0) {
      for (let j = 0; j < datas[i].children.length; j++) {
        if (matched.some(item => item.path === datas[i].children[j].route)) {
          result = datas[i].children[j].title;
        }
      }
    }
  }
  return result;
};

router.beforeEach((to, from, next) => {
  ViewUI.LoadingBar.start();

  // 修改title
  const matched = findRouteTitle(consts.SIDEBAR_MENUS, to.matched);
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!auth.loggedIn()) {
      next({
        path: 'login',
        query: { redirect: to.fullPath }
      });
    } else {
      // 检查权限，防止使用url直接访问
      if (!store.getters.isManager && matched && store.getters.accessRouter.indexOf(matched) < 0) {
        next({ path: '/error-page/403' });
        return;
      }
      next();
      document.title = matched ? `${matched}-${consts.TITLE}` : consts.TITLE;
    }
  } else {
    next();
    document.title = matched ? `${matched}-${consts.TITLE}` : consts.TITLE;
  }
});

router.afterEach((to, from, next) => {
  ViewUI.LoadingBar.finish();
});

export default router;
